package util

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"ops.alert.center.service/internal/model"
	"strconv"
	"strings"
	"time"
)

var SendAccessToken model.AccessToken
var request2 = &model.WeixinTextRequest{}

//拼接告警中心模板
func Pingjietemplate(Status, SystemAlias, Env, AlertContent, EventDatasource, EventOccurIp, EventDatasourceName, Category, time string, number int, important int) (Template, Subject string) {
	if important == 1 {
		Template = fmt.Sprintf("！！！！！！重点告警！！！！！！<br/><br/>**状态**:%s"+"<br/>告警时间:%s<br/>"+"类别:%s<br/>"+"告警环境:%s<br/>"+
			"告警应用:%s<br/>"+
			"告警源:%s<br/>"+
			"告警源名称:%s<br/>"+
			"告警IP:%s<br/>"+
			"******告警详情*****:<br/>"+
			"%s<br/><br/>", Status, time, Category, Env, SystemAlias, EventDatasource, EventDatasourceName, EventOccurIp, AlertContent)
	} else {
		Template = fmt.Sprintf("<br/>**状态**:%s<br/>"+"<br/>告警时间:%s<br/>"+"类别:%s<br/>"+"告警环境:%s<br/>"+
			"告警应用:%s<br/>"+
			"告警源:%s<br/>"+
			"告警源名称:%s<br/>"+
			"告警IP:%s<br/>"+
			"******告警详情*****:<br/>"+
			"%s<br/><br/>", Status, time, Category, Env, SystemAlias, EventDatasource, EventDatasourceName, EventOccurIp, AlertContent)
	}

	Subject = fmt.Sprintf("告警环境:%s,告警应用:%s", Env, SystemAlias)
	if len(Template) > 1000 {
		Template = Template[:300] + "(由于字数限制,详情请查看日志!)"
	}
	if EventDatasource != "zabbix" {
		Template = Template + "<br/>" +
			fmt.Sprintf("<a target=\"_blank\" href=\"http://logquery.ops.zhaogangren.com/query/applogPage?systemAlias=%s&level=3&runEnv=1\">点击查看详情</a>", SystemAlias)
	}
	if number == 1 {
		return
	}
	Template = strings.Replace(Template, "<br/>", "\n", -1)
	return
}

func UniversalPingjietemplate(topic, Env, AlertContent, EventOccurIp, Eventcaller, Category, time string, number int) (Template string) {
	Template = fmt.Sprintf("***通用告警***<br/><br/>告警主题:%s"+"<br/>告警时间:%s<br/>"+"类别:%s<br/>"+"告警环境:%s<br/>"+
		"告警IP:%s<br/>"+
		"告警人:%s<br/>"+
		"******告警详情*****:<br/>"+
		"%s<br/><br/>", topic, time, Category, Env, EventOccurIp, Eventcaller, AlertContent)
	if number == 1 {
		return
	}
	Template = strings.Replace(Template, "<br/>", "\n", -1)
	return
}

//获取发送告警中心消息的token
func GetSendAccessToken() error {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("Function_error", "GetSendAccessToken", fmt.Sprintln(GetSendAccessToken))
		}
	}()
	// 告警中心的企业微信应用token
	var url = fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s",
		"ww88ab4482196f4543", "SO4Ebq7a_M9hyJY5MzJSqD-JYzS8HEDLbktqJfqmlyE")
	bytes, err := http.Get(url)
	if err != nil {
		fmt.Println("获取告警中心发送数据的token错误", err)
		return err
	}
	data, _ := ioutil.ReadAll(bytes.Body)
	json.Unmarshal(data, &SendAccessToken)
	return nil
}

func SendWeixinText(weixinModel *model.WeixinTextRequest) error {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("Function_error", "SendWeixinText", fmt.Sprintln(SendWeixinText))
		}
	}()
	err := GetSendAccessToken()
	if err != nil {
		fmt.Println("GetSendAccessToken error")
		return err
	}
	var s1 = model.Text{
		Content: fmt.Sprintf("%s", weixinModel.Content),
	}
	jsonByte, _ := json.Marshal(s1)
	jsonStr := string(jsonByte)
	fmt.Println("jsonStr", jsonStr)
	post := make(map[string]interface{})
	post["touser"] = strings.Join(weixinModel.ToUsers, "|")
	post["toparty"] = strings.Join(weixinModel.ToPartys, "|")
	post["totag"] = strings.Join(weixinModel.ToTags, "|")
	post["msgtype"] = "text"
	post["agentid"] = 1000004
	post["text"] = &model.Text{
		Content: fmt.Sprintf("%s", weixinModel.Content),
	}
	post["safe"] = 0
	dataType, _ := json.Marshal(post)
	dataString := string(dataType)
	var jsonstr = []byte(dataString)
	buffer := bytes.NewBuffer(jsonstr)
	var Url = fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", SendAccessToken.AccessToken)
	request, err := http.NewRequest("POST", Url, buffer)
	if err != nil {
		fmt.Printf("http.NewRequest%v", err)
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8") //添加请求头
	client := http.Client{}                                              //创建客户端
	resp, err := client.Do(request.WithContext(context.TODO()))          //发送请求
	if err != nil {
		fmt.Printf("client.Do%v", err)
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	fmt.Println("发送结果是", string(respBytes))
	if err != nil {
		fmt.Printf("ioutil.ReadAll%v", err)
	}
	var thisTextresp model.TextResp
	json.Unmarshal(respBytes, &thisTextresp)
	if thisTextresp.Code == 0 {
		return nil
	} else {
		fmt.Println("thisTextresp.Code error", thisTextresp.Msg)
		return errors.New(thisTextresp.Msg)
	}
}

func SendWeixin(weixin_content string, user_ids []string) error {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("Function_error", "SendWeixin", fmt.Sprintln(SendWeixin))
		}
	}()
	request2.ToUsers = user_ids
	request2.ToPartys = []string{}
	request2.ToTags = []string{}
	request2.Content = weixin_content
	err_weixin := SendWeixinText(request2)
	if err_weixin != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "=============发送企业微信消息错误===================", err_weixin)
		return err_weixin
	}
	return nil
}

func SendWechat(ThisEvent model.AlertEvent, userids []string) {
	//发送企业微信测试
	var Time string
	Time = time.Unix(1644837126000/1000, 0).Format("2006-01-02 15:04:05")
	wechat_template, _ := Pingjietemplate(strconv.Itoa(ThisEvent.Status),
		ThisEvent.SystemAlias,
		ThisEvent.Env, ThisEvent.AlertContent, ThisEvent.EventDatasource,
		ThisEvent.EventOccurIp,
		ThisEvent.EventDatasourceName,
		ThisEvent.EventCategory, Time, 0, 0)
	err2 := SendWeixin(wechat_template, userids)
	if err2 != nil {
		fmt.Println("发送微信失败!")
		fmt.Println(err2)
	}
}
